package org.binge.widget.util;

import org.apache.commons.lang3.StringEscapeUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by lurongyu on 16-3-11.
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {

    private static final char SEPARATOR = '_';
    private static final String CHARSET_NAME = "UTF-8";
    private static final char UNDERLINE = '_';
    /**
     * 转换为字节数组
     * @param str
     * @return
     */
    public static byte[] getBytes(String str){
        if (str != null){
            try {
                return str.getBytes(CHARSET_NAME);
            } catch (UnsupportedEncodingException e) {
                return null;
            }
        }else{
            return null;
        }
    }

    /**
     * 转换为字节数组
     * @param bytes
     * @return
     */
    public static String toString(byte[] bytes){
        try {
            return new String(bytes, CHARSET_NAME);
        } catch (UnsupportedEncodingException e) {
            return EMPTY;
        }
    }

    /**
     * 是否包含字符串
     * @param str 验证字符串
     * @param strs 字符串组
     * @return 包含返回true
     */
    public static boolean inString(String str, String... strs){
        if (str != null){
            for (String s : strs){
                if (str.equals(trim(s))){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 替换掉HTML标签方法
     */
    public static String replaceHtml(String html) {
        if (isBlank(html)){
            return "";
        }
        String regEx = "<.+?>";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(html);
        String s = m.replaceAll("");
        return s;
    }

    /**
     * 替换为手机识别的HTML，去掉样式及属性，保留回车。
     * @param html
     * @return
     */
    public static String replaceMobileHtml(String html){
        if (html == null){
            return "";
        }
        return html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>");
    }

    /**
     * 缩略字符串（不区分中英文字符）
     * @param str 目标字符串
     * @param length 截取长度
     * @return
     */
    public static String abbr(String str, int length) {
        if (str == null) {
            return "";
        }
        try {
            StringBuilder sb = new StringBuilder();
            int currentLength = 0;
            for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) {
                currentLength += String.valueOf(c).getBytes("GBK").length;
                if (currentLength <= length - 3) {
                    sb.append(c);
                } else {
                    sb.append("");
                    break;
                }
            }
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 转换为Double类型
     */
    public static Double toDouble(Object val){
        if (val == null){
            return 0D;
        }
        try {
            return Double.valueOf(trim(val.toString()));
        } catch (Exception e) {
            return 0D;
        }
    }

    /**
     * 转换为Float类型
     */
    public static Float toFloat(Object val){
        return toDouble(val).floatValue();
    }

    /**
     * 转换为Long类型
     */
    public static Long toLong(Object val){
        return toDouble(val).longValue();
    }

    /**
     * 转换为Integer类型
     */
    public static Integer toInteger(Object val){
        return toLong(val).intValue();
    }



    /**
     * 驼峰命名法工具
     * @return
     * 		toCamelCase("hello_world") == "helloWorld"
     * 		toCapitalizeCamelCase("hello_world") == "HelloWorld"
     * 		toUnderScoreCase("helloWorld") = "hello_world"
     */
    public static String toCamelCase(String s) {
        if (s == null) {
            return null;
        }

        s = s.toLowerCase();

        StringBuilder sb = new StringBuilder(s.length());
        boolean upperCase = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (c == SEPARATOR) {
                upperCase = true;
            } else if (upperCase) {
                sb.append(Character.toUpperCase(c));
                upperCase = false;
            } else {
                sb.append(c);
            }
        }

        return sb.toString();
    }

    /**
     * 驼峰命名法工具
     * @return
     * 		toCamelCase("hello_world") == "helloWorld"
     * 		toCapitalizeCamelCase("hello_world") == "HelloWorld"
     * 		toUnderScoreCase("helloWorld") = "hello_world"
     */
    public static String toCapitalizeCamelCase(String s) {
        if (s == null) {
            return null;
        }
        s = toCamelCase(s);
        return s.substring(0, 1).toUpperCase() + s.substring(1);
    }

    /**
     * 驼峰命名法工具
     * @return
     * 		toCamelCase("hello_world") == "helloWorld"
     * 		toCapitalizeCamelCase("hello_world") == "HelloWorld"
     * 		toUnderScoreCase("helloWorld") = "hello_world"
     */
    public static String toUnderScoreCase(String s) {
        if (s == null) {
            return null;
        }

        StringBuilder sb = new StringBuilder();
        boolean upperCase = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            boolean nextUpperCase = true;

            if (i < (s.length() - 1)) {
                nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
            }

            if ((i > 0) && Character.isUpperCase(c)) {
                if (!upperCase || !nextUpperCase) {
                    sb.append(SEPARATOR);
                }
                upperCase = true;
            } else {
                upperCase = false;
            }

            sb.append(Character.toLowerCase(c));
        }

        return sb.toString();
    }

    /**
     * 如果不为空，则设置值
     * @param target
     * @param source
     */
    public static void setValueIfNotBlank(String target, String source) {
        if (isNotBlank(source)){
            target = source;
        }
    }

    /**
     * 转换为JS获取对象值，生成三目运算返回结果
     * @param objectString 对象串
     *   例如：row.user.id
     *   返回：!row?'':!row.user?'':!row.user.id?'':row.user.id
     */
    public static String jsGetVal(String objectString){
        StringBuilder result = new StringBuilder();
        StringBuilder val = new StringBuilder();
        String[] vals = split(objectString, ".");
        for (int i=0; i<vals.length; i++){
            val.append("." + vals[i]);
            result.append("!"+(val.substring(1))+"?'':");
        }
        result.append(val.substring(1));
        return result.toString();
    }

    /**
     * 将字符串数组按指定格式合并
     * */
    public static final String connectStrArray(String[] strs,String splitFlag){
        if(strs!=null && strs.length>0){
            StringBuilder stringBuilder = new StringBuilder();
            for(int i=0;i<strs.length;i++){
                stringBuilder.append(strs[i]);
                if(i<strs.length-1){
                    stringBuilder.append(splitFlag);
                }
            }
            return stringBuilder.toString();
        }
        return "";
    }

    /**
     * 将驼峰法字符串按照下划线分割，除第一个字符外
     * */
    public static final String camelToUnderline(String param){
        if(StringUtils.isEmpty(param)){
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for(int i=0;i<len;i++){
            char c = param.charAt(i);
            if(Character.isUpperCase(c)){
                if(i!=0) {
                    sb.append(UNDERLINE);
                }
                sb.append(Character.toLowerCase(c));
            }else{
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 将按下划线分割字符串按照驼峰法命名
     * */
    public static final String underlineToCamel(String param){
        if(StringUtils.isEmpty(param)){
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for(int i=0;i<len;i++){
            char c = param.charAt(i);
            if(c==UNDERLINE){
                if(++i<len){
                    sb.append(Character.toUpperCase(param.charAt(i)));
                }
            }else{
                if(i==0){
                    sb.append(Character.toUpperCase(param.charAt(i)));
                }else{
                    sb.append(c);
                }
            }
        }
        return sb.toString();
    }

    //add
    public static String[] getParamFromString(String aSourceString, String aStartStr, String aEndStr)
    {
        aSourceString = (new StringBuilder()).append(aSourceString).append(aEndStr).toString();
        String strSource = aSourceString;
        ArrayList strKey = new ArrayList();
        int iStartIndex = strSource.indexOf(aStartStr);
        int iStartLength = aStartStr.length();
        int iEndLength = aEndStr.length();
        String strTemp = "";
        strTemp = strSource.substring(iStartIndex + iStartLength, strSource.length());
        int iEndIndex = strTemp.indexOf(aEndStr) + strSource.substring(0, iStartIndex + iStartLength).length();
        if(iEndIndex == iStartIndex)
            strKey.add(strTemp);
        for(; iStartIndex != -1 && iEndIndex != -1 && iStartIndex < iEndIndex; iEndIndex = strTemp.indexOf(aEndStr) + strSource.substring(0, iStartIndex + iStartLength).length())
        {
            strTemp = strSource.substring(iStartIndex + iStartLength, iEndIndex);
            strKey.add(strTemp);
            strSource = strSource.substring(iEndIndex + iEndLength, strSource.length());
            iStartIndex = strSource.indexOf(aStartStr);
            strTemp = strSource.substring(iStartIndex + iStartLength, strSource.length());
        }

        return (String[])(String[])strKey.toArray(new String[0]);
    }



    public static String substringAfter(String str, String separator)
    {
        if(isEmpty(str))
            return str;
        if(separator == null)
            return "";
        int pos = str.indexOf(separator);
        if(pos == -1)
            return "";
        else
            return str.substring(pos + separator.length());
    }

    public static void main(String[] args) throws Exception{
        System.out.println(substring("wwwww.txt",0,5) );
    }
}
